home *** CD-ROM | disk | FTP | other *** search
- Path: nrd.ups.com!nrd1rls
- From: nrd1rls@nrd.ups.com (Richard Siddall Contractor)
- Newsgroups: comp.lang.c++
- Subject: Re: Help: File counting lines
- Date: 18 Mar 1996 17:04:23 GMT
- Organization: United Parcel Service Research & Development
- Message-ID: <4ik52n$6ab@casey.nrd.ups.com>
- References: <4hni12$qst@bolivia.it.earthlink.net> <4huog1$t8s@news.axess.com>
- NNTP-Posting-Host: rufus.nrd.ups.com
- X-Newsreader: TIN [version 1.2 PL2]
-
- Kamikaze (tdrymona@axess.com) wrote:
- : brunop@earthlink.net (Peter Bruno) wrote:
-
- : >Does anyone have any suggestions on a fast way to count the number of lines in
- : >a ASCII file. Each line is terminted by a <enter> and all I need to do is
- : >count the number of lines (records) in the file.
-
- : >The way I've been doing it is by: fgets(row, 128, File); count++;
- : >however, if the line is longer then 128 characters this does not work and it
- : >would seem that there must be a better way of doing it anyway... perhaps by
- : >incrementing the pointer until EOF??
-
- Your problem is that if fgets() reads a line longer than the buffer
- you pass to it, it splits the line. Therefore, you need to pass a
- buffer longer than your longest line to fgets() if you wish to use
- the number of fgets() calls as the count of lines.
-
- Alternately, you could check that the last character in the buffer
- (before the string terminator) is a newline: if so, fgets() did not
- split the line.
-
- The conventional was is to use fgetc() and examine each character so
- see if it is a newline (the equivalent of Enter).
-
- : Yeah use the stream objects, like this
-
- : ifstream in;
- : int count = 0;
- : char buffer[BUFFER_SIZE );
-
- : in = open( name_of_file );
- : if ( !in.bad() )
- : {
- : while ( !in.eof() )
- : {
- : getline( buffer, sizeof( buffer ) );
- : count++;
- : }
- : in.close();
- : }
-
- This has the same problem as the fgets() approach.
-
- Just my 0.02 ECUs.
-
- Richard Siddall.
-